package csu.web.credit_bank.controller;

import csu.web.credit_bank.pojo.LearningProgress;
import csu.web.credit_bank.service.LearningProgressService;
import csu.web.credit_bank.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/learning-progress")
public class LearningProgressController {

    @Autowired
    private LearningProgressService learningProgressService;

    @PostMapping("/record-view")
    public Result<Void> recordResourceView(@RequestBody Map<String, String> payload) {
        String studentId = payload.get("studentId");
        String courseId = payload.get("courseId");
        String resourceId = payload.get("resourceId");

        if (studentId == null || courseId == null || resourceId == null) {
            return Result.failure("参数不完整");
        }

        try {
            learningProgressService.updateProgressAfterResourceView(studentId, courseId, resourceId);
            return Result.success("学习记录成功");
        } catch (Exception e) {
            return Result.failure("更新学习进度时出错: " + e.getMessage());
        }
    }

    @PostMapping
    public Result<LearningProgress> createOrUpdateProgress(@RequestBody LearningProgress progress) {
        try {
            LearningProgress result = learningProgressService.createOrUpdateProgress(progress);
            return Result.success("进度更新成功", result);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @GetMapping
    public Result<LearningProgress> getProgress(@RequestParam String studentId, @RequestParam String courseId) {
        LearningProgress progress = learningProgressService.getProgress(studentId, courseId);
        return progress != null ? Result.success(progress) : Result.failure("未找到相关进度记录");
    }

    @GetMapping("/students/{studentId}")
    public Result<List<LearningProgress>> getStudentProgressList(@PathVariable String studentId) {
        return Result.success(learningProgressService.getProgressByStudent(studentId));
    }

    @DeleteMapping
    public Result<Void> deleteProgress(@RequestParam String studentId, @RequestParam String courseId) {
        boolean success = learningProgressService.deleteProgress(studentId, courseId);
        return success ? Result.success("进度删除成功") : Result.failure("进度删除失败");
    }
}
